package com.express.core.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.express.aop.AuthToken;
import com.express.common.SysParamterUtil;
import com.express.common.result.Result;
import com.express.constants.Constants;
import com.express.dto.*;
import com.express.entity.UserReceipt;
import com.express.service.IAccountService;
import com.express.service.IOrderService;
import com.express.service.IWxUserService;
import com.express.service.UserReceiptService;
import com.express.vo.TokenVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * api控制类
 */
@RestController
@RequestMapping("/api")
//@Api(tags = "api管理", value = "api管理相关接口")
public class ExpApiController {

    private static final Logger logger = LoggerFactory.getLogger(ExpApiController.class);

    @Autowired
    IOrderService orderService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    UserReceiptService userReceiptService;
    @Autowired
    IAccountService accountService;
    @Autowired
    SysParamterUtil paramterUtil;

    /**
     * 认证接口
     *
     * @return
     */
    @PostMapping(value = "validate")
    public Result validate(@RequestBody @Valid LoginValidateDto validateDto, Errors bindingResult) {
        // 验证是否通过
        if (bindingResult.hasErrors()) {
            return Result.error(201, bindingResult.getAllErrors().get(0).getDefaultMessage(), false);
        }
        TokenVo vo = wxUserService.validate(validateDto);
        if (vo == null) {
            return Result.error(500, "账号异常", null);
        }
        return Result.ok(vo);
    }

    /**
     * 面单
     *
     * @return
     */
    @PostMapping(value = "label")
    public Result labelOrder(@Valid Label100OrderDto orderDto, Errors bindingResult) {
        return Result.ok(orderService.labelOrder(orderDto), bindingResult);
    }

    /**
     * 查询
     *
     * @return
     */
    @PostMapping("query")
    public Result queryOrder(@Valid Query100OrderDto orderDto, Errors bindingResult) {
        return Result.ok(orderService.queryOrder(orderDto), bindingResult);
    }

    /**
     * 根据手机号查询快递
     *
     * @return
     */
    @PostMapping(value = "query/phone")
    public Result queryKauidi(@Valid Query100ByPhoneOrderDto orderDto, Errors bindingResult) {
        return Result.ok(orderService.queryOrderByPhone(orderDto), bindingResult);
    }

    /**
     * 获取订单
     *
     * @return
     */
    @AuthToken(source = 1)
    @GetMapping(value = "/order/｛orderId｝")
    public Result getOrderById(@PathVariable("orderId") String orderId) {
        return Result.ok(orderService.getOrderByAppointNo(orderId));
    }

    /**
     * 更新订单
     *
     * @return
     */
    @AuthToken(source = 1)
    @PostMapping(value = "/order/update")
    public Result update(@RequestBody @Valid UpdateOrderDto orderDto, Errors bindingResult) {
        return Result.ok(orderService.updateByAppointNo(orderDto), bindingResult);
    }

    /**
     * 发货接口
     *
     * @return
     */
    @AuthToken(source = 1)
    @PostMapping(value = "delivery")
    public Result delivery(@RequestBody @Valid UserReceipt userReceipt, Errors bindingResult) {
        Result result = null;
        logger.info("收到发货请求：{}", JSON.toJSONString(userReceipt));
        try {
            // 验证是否通过
            if (bindingResult.hasErrors()) {
                return Result.error(201, bindingResult.getAllErrors().get(0).getDefaultMessage(), false);
            }
            if (StringUtils.isBlank(userReceipt.getOddNumber())) {
                String oddNumber = paramterUtil.getParametValue(Constants.ENV_ORDER, true).toString();
                paramterUtil.setParametValue(Constants.ENV_ORDER, oddNumber);
                userReceipt.setOddNumber(oddNumber);
            }
            int num = userReceiptService.save(userReceipt);
            if (num <= 0) {
                result = Result.error(500, "账号异常", null);
                return result;
            }
            // 返回 一个运单号
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("billNumber", userReceipt.getOddNumber());
            logger.info("返回发货结果：{}", userReceipt.getOddNumber());
            result = Result.ok(jsonObject);
        } catch (Exception e) {
            logger.error("发货失败", e);
            result = Result.error(500, "发货异常", null);
        }
        return result;
    }
}
